package com.zx.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zx.reggie.common.R;
import com.zx.reggie.pojo.Category;
import com.zx.reggie.pojo.Dish;
import com.zx.reggie.pojo.DishDto;
import com.zx.reggie.pojo.DishFlavor;
import com.zx.reggie.service.CategoryService;
import com.zx.reggie.service.DishFlavorService;
import com.zx.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author 张旭
 * @version 1.0
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping
    @CacheEvict(value = "dish",key = "#dishDto.getCategoryId()+'_'+#dishDto.status")
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);

        /*//实现精准删除
        String key ="dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
*/
        return R.success("新增菜品成功");
    }

    @GetMapping("/page")
    public R<Page> getALL(int page, int pageSize, String name) {

        //构造分页构造器对象
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();

        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.like(name != null, Dish::getName, name);
        //添加排序条件
        queryWrapper.orderByDesc(Dish::getUpdateTime);

        //执行分页查询
        dishService.page(pageInfo, queryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");

        List<Dish> records = pageInfo.getRecords();

        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item, dishDto);

            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);

            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);
    }


    @GetMapping("/{id}")
    public R<DishDto> goBack(@PathVariable long id) {
        DishDto dishDto = dishService.getBack(id);
        return R.success(dishDto);
    }


    @PutMapping
    @CacheEvict(value = "dish",key = "#dishDto.getCategoryId()+'_'+#dishDto.status")
    public R<String> update(@RequestBody DishDto dishDto) {
        dishService.updateWithFlavor(dishDto);

     /*   //实现精准删除
        String key ="dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
*/
        return R.success("菜品信息修改成功");
    }

    /**
     * 修改菜品状态
     * @param status 前端传输的状态码
     * @param ids 需要修改的菜品
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> setStatus(@PathVariable Integer status, String ids) {
        String[] split = ids.split(",");

        for (String s : split) {
            Dish byId = dishService.getById(s);
            byId.setStatus(status);
            dishService.updateById(byId);
        }
        return R.success("菜品状态修改成功");
    }

   /* @DeleteMapping
    public R<String> delete(String ids) {
        String[] split = ids.split(",");
        ArrayList<String> list = new ArrayList<>();
        for (String s : split) {
            list.add(s);
        }
        dishService.removeByIds(list);
        return R.success("删除成功");
    }
*/

    @DeleteMapping
    @CacheEvict(value = "dish",key = "#dishDto.getCategoryId()+'_'+#dishDto.status")
    public R<String> delete(@RequestParam List<Long> ids) {
        dishService.removeWithFlavor(ids);
        return R.success("删除成功");
    }

    /* @GetMapping("/list")
     public R<List<Dish>> getList(Dish dish){

         LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
         lambdaQueryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
         lambdaQueryWrapper.eq(Dish::getStatus,1);
         lambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
         List<Dish> list = dishService.list(lambdaQueryWrapper);

         return R.success(list);
     }
 */
    @GetMapping("/list")
    @Cacheable(value = "dish", key = "#dish.categoryId+'_'+#dish.status")
    public R<List<DishDto>> getList(Dish dish) {
        List<DishDto> dishDtoList = null;

      /*  //动态构造key
        String key ="dish_"+dish.getCategoryId()+"_"+dish.getStatus();

        //先从redis中获取缓存数据
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);

        if(dishDtoList != null){
            return R.success(dishDtoList);
        }
*/
        //根据菜品分类id查到该分类下所有的菜品
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        lambdaQueryWrapper.eq(Dish::getStatus, 1);
        lambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(lambdaQueryWrapper);


        //创建要返回的集合，包含菜品口味
        dishDtoList = new ArrayList<>();
        for (Dish dish1 : list) {

            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(dish1, dishDto);

            //根据id查询分类对象
            Long categoryId = dish1.getCategoryId();//分类id
            Category category = categoryService.getById(categoryId);

            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            //根据菜品id去查该菜品所有的口味
            Long id = dishDto.getId();
            LambdaUpdateWrapper<DishFlavor> dishFlavorLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            dishFlavorLambdaUpdateWrapper.eq(DishFlavor::getDishId, id);
            List<DishFlavor> list1 = dishFlavorService.list(dishFlavorLambdaUpdateWrapper);
            dishDto.setFlavors(list1);

            dishDtoList.add(dishDto);
        }

   /*     //如果不存在，需要查询数据库，将查询到的菜品数据缓存到redis
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);
*/
        return R.success(dishDtoList);
    }

}
